//
// Created by Administrator on 2021/11/4.
//

#include "GridHelper.h"

GridHelper::GridHelper(float size, int divisions, Color colorCenterLine, Color colorGrid) {
    type = GET_CLASS(__FILE__);
    name = type + "_" + id;

    this->size = size;
    this->divisions = divisions;
    this->colorCenterLine = colorCenterLine;
    this->colorGrid = colorGrid;
}

void GridHelper::onInit() {
    if(!geometries.empty()) {
        for (auto iterator = geometries.begin(); iterator != geometries.end(); iterator ++) {
            if (NULL != *iterator) {
                SAFE_DELETE(*iterator);
            }
        }
        std::vector<BufferGeometry *>().swap(geometries);
    }

    BufferGeometry *geometry = new BufferGeometry();
    geometry->drawMode = GL_LINES;
    geometry->polygonMode = GL_LINE;

    int center = divisions / 2;
    float step = size / divisions;
    float halfSize = size / 2;

    for ( int i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {

        geometry->vertices.push_back(- halfSize);
        geometry->vertices.push_back(0);
        geometry->vertices.push_back(k);
        geometry->vertices.push_back(halfSize);
        geometry->vertices.push_back(0);
        geometry->vertices.push_back(k);

        geometry->vertices.push_back(k);
        geometry->vertices.push_back(0);
        geometry->vertices.push_back(- halfSize);
        geometry->vertices.push_back(k);
        geometry->vertices.push_back(0);
        geometry->vertices.push_back(halfSize);

        j += 3 * 4;
    }

    geometries.push_back(geometry);
    Object3D::onInit();
}

void GridHelper::drawUI() {
    Object3D::drawUI();

    bool refreshAttri = false;
    if(ImGui::SliderFloat("Size", &size, 0.01f, 100.0f)){
        refreshAttri = true;
    }
    if(ImGui::SliderInt("Divisions", &divisions, 1, 100)){
        refreshAttri = true;
    }

    if(refreshAttri){
        onInit();
    }
}


